<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { Link, usePage, router } from '@inertiajs/vue3'
import { Menu, MenuButton, MenuItems, MenuItem, Dialog, DialogPanel, TransitionChild, TransitionRoot } from '@headlessui/vue'
import Notification from '@/Components/UI/Notification.vue'
import GlobalSearch from '@/Components/Features/GlobalSearch.vue'
import {
    MagnifyingGlassIcon,
    Bars3Icon,
    XMarkIcon,
    BellIcon,
    ChevronDownIcon,
    HomeIcon,
    DocumentTextIcon,
    FolderIcon,
    TagIcon,
    DocumentIcon,
    UserGroupIcon,
    ArrowRightOnRectangleIcon,
    UserIcon
} from '@heroicons/vue/24/outline'

const page = usePage()
const user = computed(() => page.props.auth.user)

// 获取当前路由名称
const currentRoute = computed(() => route().current())

// 检查路由是否激活
const isRouteActive = (routeName) => {
    if (!currentRoute.value) return false
    if (typeof routeName === 'string') {
        return currentRoute.value === routeName
    }
    return routeName.some(name => currentRoute.value.startsWith(name))
}

// 导航菜单配置 - 使用 Heroicons 组件
const navigation = [
    {
        name: '仪表盘',
        href: route('admin.dashboard'),
        icon: HomeIcon,
        matchRoutes: ['admin.dashboard']
    },
    {
        name: '文章管理',
        href: route('admin.posts.index'),
        icon: DocumentTextIcon,
        matchRoutes: ['admin.posts.']
    },
    {
        name: '分类管理',
        href: route('admin.categories.index'),
        icon: FolderIcon,
        matchRoutes: ['admin.categories.']
    },
    {
        name: '标签管理',
        href: route('admin.tags.index'),
        icon: TagIcon,
        matchRoutes: ['admin.tags.']
    },
    {
        name: '页面管理',
        href: route('admin.pages.index'),
        icon: DocumentIcon,
        matchRoutes: ['admin.pages.']
    },
    {
        name: '用户管理',
        href: route('admin.users.index'),
        icon: UserGroupIcon,
        matchRoutes: ['admin.users.']
    }
]

// 用户菜单
const userNavigation = [
    { name: '个人资料', href: route('profile.show'), icon: UserIcon },
    { name: '返回前台', href: route('blog.home') },
    { name: '退出登录', href: route('logout'), method: 'post', icon: ArrowRightOnRectangleIcon }
]

// 移动端侧边栏状态
const sidebarOpen = ref(false)

// 切换侧边栏
const toggleSidebar = () => {
    sidebarOpen.value = !sidebarOpen.value
}

// 关闭侧边栏
const closeSidebar = () => {
    sidebarOpen.value = false
}

const logout = () => {
    router.post(route('logout'))
}

const notification = ref(null)

// 监听 flash 消息变化
watch(() => usePage().props.flash, (flash) => {
    if (flash?.success) {
        notification.value?.showNotification('success', flash.success)
    }
    if (flash?.error) {
        notification.value?.showNotification('error', flash.error)
    }
}, { deep: true })

// 暴露通知方法给子组件
const showNotification = (type, message) => {
    notification.value?.showNotification(type, message)
}

// 检测是否为 Mac 系统
const isMac = computed(() => {
    return typeof window !== 'undefined' && window.navigator.platform.toUpperCase().indexOf('MAC') >= 0
})

const showSearch = ref(false)

// 处理快捷键
const onKeydown = (event) => {
    if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault()
        showSearch.value = true
    }
    if (event.key === 'Escape' && sidebarOpen.value) {
        closeSidebar()
    }
}

onMounted(() => {
    document.addEventListener('keydown', onKeydown)
})

onUnmounted(() => {
    document.removeEventListener('keydown', onKeydown)
})

defineExpose({ showNotification })
</script>

<template>
    <div class="min-h-screen bg-gray-50">
        <!-- 移动端侧边栏遮罩 -->
        <TransitionRoot :show="sidebarOpen" as="template">
            <Dialog as="div" class="relative z-50 lg:hidden" @close="closeSidebar">
                <TransitionChild
                    as="template"
                    enter="transition-opacity ease-linear duration-300"
                    enter-from="opacity-0"
                    enter-to="opacity-100"
                    leave="transition-opacity ease-linear duration-300"
                    leave-from="opacity-100"
                    leave-to="opacity-0"
                >
                    <div class="fixed inset-0 bg-gray-900/80" />
                </TransitionChild>

                <div class="fixed inset-0 flex">
                    <TransitionChild
                        as="template"
                        enter="transition ease-in-out duration-300 transform"
                        enter-from="-translate-x-full"
                        enter-to="translate-x-0"
                        leave="transition ease-in-out duration-300 transform"
                        leave-from="translate-x-0"
                        leave-to="-translate-x-full"
                    >
                        <DialogPanel class="relative mr-16 flex w-full max-w-xs flex-1">
                            <TransitionChild
                                as="template"
                                enter="ease-in-out duration-300"
                                enter-from="opacity-0"
                                enter-to="opacity-100"
                                leave="ease-in-out duration-300"
                                leave-from="opacity-100"
                                leave-to="opacity-0"
                            >
                                <div class="absolute left-full top-0 flex w-16 justify-center pt-5">
                                    <button type="button" class="-m-2.5 p-2.5" @click="closeSidebar">
                                        <span class="sr-only">关闭侧边栏</span>
                                        <XMarkIcon class="h-6 w-6 text-white" aria-hidden="true" />
                                    </button>
                                </div>
                            </TransitionChild>
                            
                            <!-- 移动端侧边栏内容 -->
                            <div class="flex grow flex-col gap-y-5 overflow-y-auto border-r border-gray-200 bg-white px-6 pb-4">
                                <!-- Logo -->
                                <div class="flex h-16 shrink-0 items-center">
                                    <Link :href="route('admin.dashboard')" class="flex items-center gap-x-2" @click="closeSidebar">
                                        <div class="h-8 w-8 rounded-lg bg-orange-600 flex items-center justify-center">
                                            <span class="text-white font-bold text-sm">{{ page.props.app.name?.charAt(0) || 'B' }}</span>
                                        </div>
                                        <span class="text-xl font-semibold text-gray-900">{{ page.props.app.name || '后台管理' }}</span>
                                    </Link>
                                </div>

                                <!-- 主导航 -->
                                <nav class="flex flex-1 flex-col">
                                    <ul role="list" class="flex flex-1 flex-col gap-y-1">
                                        <li v-for="item in navigation" :key="item.name">
                                            <Link
                                                :href="item.href"
                                                :class="[
                                                    isRouteActive(item.matchRoutes)
                                                        ? 'bg-orange-50 text-orange-600'
                                                        : 'text-gray-700 hover:text-orange-600 hover:bg-gray-50',
                                                    'group flex gap-x-3 rounded-md p-3 text-sm leading-6 font-semibold transition-colors'
                                                ]"
                                                @click="closeSidebar"
                                            >
                                                <component
                                                    :is="item.icon"
                                                    :class="[
                                                        isRouteActive(item.matchRoutes) ? 'text-orange-600' : 'text-gray-400 group-hover:text-orange-600',
                                                        'h-6 w-6 shrink-0'
                                                    ]"
                                                />
                                                {{ item.name }}
                                            </Link>
                                        </li>
                                    </ul>
                                </nav>
                            </div>
                        </DialogPanel>
                    </TransitionChild>
                </div>
            </Dialog>
        </TransitionRoot>

        <!-- 桌面端侧边栏 -->
        <div class="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-72 lg:flex-col">
            <div class="flex grow flex-col gap-y-5 overflow-y-auto border-r border-gray-200 bg-white px-6 pb-4">
                <!-- Logo -->
                <div class="flex h-16 shrink-0 items-center">
                    <Link :href="route('admin.dashboard')" class="flex items-center gap-x-2">
                        <div class="h-8 w-8 rounded-lg bg-orange-600 flex items-center justify-center">
                            <span class="text-white font-bold text-sm">{{ page.props.app.name?.charAt(0) || 'B' }}</span>
                        </div>
                        <span class="text-xl font-semibold text-gray-900">{{ page.props.app.name || '后台管理' }}</span>
                    </Link>
                </div>

                <!-- 主导航 -->
                <nav class="flex flex-1 flex-col">
                    <ul role="list" class="flex flex-1 flex-col gap-y-1">
                        <li v-for="item in navigation" :key="item.name">
                            <Link
                                :href="item.href"
                                :class="[
                                    isRouteActive(item.matchRoutes)
                                        ? 'bg-orange-50 text-orange-600'
                                        : 'text-gray-700 hover:text-orange-600 hover:bg-gray-50',
                                    'group flex gap-x-3 rounded-md p-3 text-sm leading-6 font-semibold transition-colors'
                                ]"
                            >
                                <component
                                    :is="item.icon"
                                    :class="[
                                        isRouteActive(item.matchRoutes) ? 'text-orange-600' : 'text-gray-400 group-hover:text-orange-600',
                                        'h-6 w-6 shrink-0'
                                    ]"
                                />
                                {{ item.name }}
                            </Link>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>

        <!-- 主内容区 -->
        <div class="lg:pl-72">
            <!-- 顶部导航栏 -->
            <div class="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-x-4 border-b border-gray-200 bg-white px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8">
                <!-- 移动端菜单按钮 -->
                <button
                    type="button"
                    class="-m-2.5 p-2.5 text-gray-700 lg:hidden"
                    @click="toggleSidebar"
                >
                    <span class="sr-only">打开侧边栏</span>
                    <Bars3Icon class="h-6 w-6" aria-hidden="true" />
                </button>

                <!-- 分隔线 -->
                <div class="h-6 w-px bg-gray-200 lg:hidden" aria-hidden="true" />

                <div class="flex flex-1 gap-x-4 self-stretch lg:gap-x-6">
                    <div class="flex flex-1"></div>
                    <div class="flex items-center gap-x-4 lg:gap-x-6">
                        <!-- 搜索按钮 -->
                        <button
                            type="button"
                            class="flex items-center gap-x-2 rounded-md px-3 py-2 text-sm font-medium text-gray-400 hover:text-gray-500 hover:bg-gray-50 transition-colors"
                            @click="showSearch = true"
                        >
                            <MagnifyingGlassIcon class="h-5 w-5" aria-hidden="true" />
                            <span class="sr-only">全局搜索</span>
                            <kbd class="hidden sm:inline-flex items-center gap-1 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono text-[10px] font-medium text-gray-400">
                                {{ isMac ? '⌘K' : 'Ctrl K' }}
                            </kbd>
                        </button>

                        <!-- 通知按钮 -->
                        <button type="button" class="-m-2.5 p-2.5 text-gray-400 hover:text-gray-500">
                            <span class="sr-only">查看通知</span>
                            <BellIcon class="h-6 w-6" aria-hidden="true" />
                        </button>

                        <!-- 分隔线 -->
                        <div class="hidden lg:block lg:h-6 lg:w-px lg:bg-gray-200" aria-hidden="true" />
                        
                        <!-- 用户菜单 -->
                        <Menu as="div" class="relative">
                            <MenuButton class="-m-1.5 flex items-center gap-x-4 p-1.5 text-sm font-semibold leading-6 text-gray-900 hover:bg-gray-50 rounded-md">
                                <span class="sr-only">打开用户菜单</span>
                                <img
                                    v-if="user?.profile_photo_url"
                                    :src="user.profile_photo_url"
                                    :alt="user?.name"
                                    class="h-8 w-8 rounded-full bg-gray-50"
                                >
                                <span
                                    v-else
                                    class="flex h-8 w-8 items-center justify-center rounded-full bg-orange-600"
                                >
                                    <span class="text-sm font-medium leading-none text-white">
                                        {{ user?.name?.charAt(0) || 'U' }}
                                    </span>
                                </span>
                                <span class="hidden lg:flex lg:items-center">
                                    <span class="ml-4 text-sm font-semibold leading-6 text-gray-900">
                                        {{ user?.name || '用户' }}
                                    </span>
                                    <ChevronDownIcon class="ml-2 h-5 w-5 text-gray-400" aria-hidden="true" />
                                </span>
                            </MenuButton>

                            <transition
                                enter-active-class="transition ease-out duration-100"
                                enter-from-class="transform opacity-0 scale-95"
                                enter-to-class="transform opacity-100 scale-100"
                                leave-active-class="transition ease-in duration-75"
                                leave-from-class="transform opacity-100 scale-100"
                                leave-to-class="transform opacity-0 scale-95"
                            >
                                <MenuItems class="absolute right-0 z-10 mt-2.5 w-48 origin-top-right rounded-md bg-white py-2 shadow-lg ring-1 ring-gray-900/5 focus:outline-none">
                                    <MenuItem v-for="item in userNavigation" :key="item.name" v-slot="{ active }">
                                        <template v-if="!item.method">
                                            <Link
                                                :href="item.href"
                                                :class="[
                                                    active ? 'bg-gray-50' : '',
                                                    'flex items-center gap-x-3 px-4 py-2 text-sm leading-6 text-gray-900'
                                                ]"
                                            >
                                                <component
                                                    v-if="item.icon"
                                                    :is="item.icon"
                                                    class="h-5 w-5 text-gray-400"
                                                />
                                                {{ item.name }}
                                            </Link>
                                        </template>
                                        <button
                                            v-else
                                            @click="logout"
                                            :class="[
                                                active ? 'bg-gray-50' : '',
                                                'flex w-full items-center gap-x-3 px-4 py-2 text-left text-sm leading-6 text-gray-900'
                                            ]"
                                        >
                                            <component
                                                v-if="item.icon"
                                                :is="item.icon"
                                                class="h-5 w-5 text-gray-400"
                                            />
                                            {{ item.name }}
                                        </button>
                                    </MenuItem>
                                </MenuItems>
                            </transition>
                        </Menu>
                    </div>
                </div>
            </div>

            <!-- 页面内容 -->
            <main class="py-8">
                <div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                    <slot />
                </div>
            </main>
        </div>

        <!-- 通知组件 -->
        <Notification ref="notification" />

        <!-- 全局搜索组件 -->
        <GlobalSearch
            :show="showSearch"
            @close="showSearch = false"
        />
    </div>
</template>
